import React, { Component } from 'react';
import { Form, Button, Drawer, Input, message, Select, Spin } from 'antd';
import AxiosUtil from '@/tool/AxiosUtil';
import SetIcon from '@/pages/sys/user/components/SetIcon';

const { Option, OptGroup } = Select;

/**
 * 添加新用户
 *
 * @author zhangby
 * @date 26/11/19 11:41 am
 */
// eslint-disable-next-line react/prefer-stateless-function
class UserEdit extends Component {
  state = {
    visible: false,
    loading: false,
    photo: '',
    userTypeList: [],
    roleList: [],
    officeList: [],
  };

  // 初始化
  editInit() {
    this.props.form.resetFields();
    this.setState({ photo: '', loading: true });
    // 查询用户类型
    AxiosUtil.get('/sys/dict/select/data/role_type')
      .then(res => {
        // eslint-disable-next-line react/no-unused-state
        this.setState({ userTypeList: res.result });
      });
    AxiosUtil.get('/sys/role/select/data')
      .then(res => {
        // eslint-disable-next-line react/no-unused-state
        this.setState({ roleList: res.result });
      });
    AxiosUtil.get('/sys/office/select/data')
      .then(res => {
        // eslint-disable-next-line react/no-unused-state
        this.setState({ officeList: res.result });
      });
    // 查询用户信息
    const { setFieldsValue } = this.props.form;
    AxiosUtil.get(`/sys/user/${this.props.userId}`).then(res => {
      const val = res.result;
      setFieldsValue({
        name: val.name,
        loginName: val.loginName,
        mobile: val.mobile,
        email: val.email,
        userType: val.userType,
        officeId: val.officeId,
        roleId: val.roleId,
        photo: val.photo,
        roleIds: val.tails.roleIds,
      });
      this.setState({ loading: false, photo: val.photo });
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    }).then(err => {
      this.setState({ loading: false });
    });
    this.showDrawer();
  }

  // 提交
  // eslint-disable-next-line react/sort-comp,@typescript-eslint/no-unused-vars
  handleSubmit = e => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-empty
      values['photo'] = this.state.photo;
      values['roleId'] = values.roleIds.join(',');
      if (!err) {
        this.setState({ loading: true });
        AxiosUtil.put(`/sys/user/${this.props.userId}`, values)
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          .then(res => {
            message.success('更新用户成功');
            this.onClose();
            this.props.queryUserList();
            this.setState({ loading: false });
          })
          // eslint-disable-next-line @typescript-eslint/no-unused-vars,no-shadow
          .catch(err => {
            console.log(err)
            this.setState({ loading: false });
          })
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };

    return (
      <span>
        {/* eslint-disable-next-line react/jsx-no-bind */}
          <span key={-1} style={{ cursor: 'pointer' }} onClick={this.editInit.bind(this)}>
            {
              this.props.children !== undefined ?
                this.props.children
              :
              <Button type="primary" shape="circle" icon="edit" style={{ marginRight: 10 }}/>
            }
          </span>
        {/* 弹出层 */}
        <Drawer
          title="编辑用户"
          placement="right"
          onClose={this.onClose}
          visible={this.state.visible}
          bodyStyle={{ paddingBottom: 80 }}
          width={600}
        >
          <Spin spinning={this.state.loading}>
            <Form {...formItemLayout}>
             <div style={{
               textAlign: 'center',
               marginBottom: 20,
             }}>
               {/* eslint-disable-next-line react/no-unused-state,max-len */}
               <SetIcon isEdit key={this.state.photo} photo={this.state.photo} renderFun={icon => this.setState({ photo: icon })}/>
             </div>
             <Form.Item label="用户名">
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '请输入用户名',
                    },
                  ],
                })(<Input/>)}
              </Form.Item>
             <Form.Item label="登录名">
                {getFieldDecorator('loginName', {
                  rules: [
                    {
                      required: true,
                      message: '请输入登录名',
                    },
                    {
                      validator: this.handleDictType,
                    },
                  ],
                })(<Input/>)}
              </Form.Item>
             <Form.Item label="联系方式">
                {getFieldDecorator('mobile', {})(<Input/>)}
              </Form.Item>
             <Form.Item label="电子邮箱">
                {getFieldDecorator('email', {})(<Input/>)}
              </Form.Item>
              <Form.Item label="所属部门">
                {getFieldDecorator('officeId', {
                  rules: [
                    {
                      required: true,
                      message: '请选择部门',
                    },
                  ],
                })(
                  <Select>
                    {
                      this.state.officeList.map((item, key) => (
                        // eslint-disable-next-line react/no-array-index-key
                        <OptGroup label={item.label} key={key}>
                          {
                            item.children.map((itm, ky) => (
                              // eslint-disable-next-line react/no-array-index-key
                              <Option value={itm.value} key={ky}>{itm.label}</Option>
                            ))
                          }
                        </OptGroup>
                      ))
                    }
                  </Select>,
                )}
              </Form.Item>
              <Form.Item label="用户类型">
                {getFieldDecorator('userType', {
                  rules: [
                    {
                      required: true,
                      message: '请选择用户类型',
                    },
                  ],
                })(
                  <Select>
                    {
                      this.state.userTypeList.map((item, key) => (
                        // eslint-disable-next-line react/no-array-index-key
                        <Option key={key} value={item.value}>{item.label}</Option>
                      ))
                    }
                  </Select>,
                )}
              </Form.Item>
              <Form.Item label="所属角色">
                {getFieldDecorator('roleIds', {
                  rules: [
                    {
                      required: true,
                      message: '请选择角色',
                    },
                  ],
                })(
                  <Select mode="multiple">
                    {
                      this.state.roleList.map((item, key) => (
                        // eslint-disable-next-line react/no-array-index-key
                        <Option key={key} value={item.value}>{item.label}</Option>
                      ))
                    }
                  </Select>,
                )}
              </Form.Item>
            </Form>
          </Spin>

          {/* 提交 */}
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.onClose} style={{ marginRight: 8 }}>
              Cancel
            </Button>
            <Button onClick={this.handleSubmit} type="primary">
              Submit
            </Button>
          </div>
        </Drawer>
      </span>
    )
  }

  // eslint-disable-next-line react/sort-comp
  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };
}

export default Form.create({ name: 'UserEdit' })(UserEdit);
